﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.SharePoint;
using System.Threading;

namespace getAllAlerts
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            setup();
        }

        private void setup()
        {
            // Set the view to show details.
            this.lvResult.View = View.Details;
            // Allow the user to edit item text.
            this.lvResult.LabelEdit = true;
            // Allow the user to rearrange columns.
            this.lvResult.AllowColumnReorder = true;
            // Display check boxes.
            this.lvResult.CheckBoxes = true;
            // Display grid lines.
            this.lvResult.GridLines = true;
            //create columns
            this.lvResult.Columns.Add("Site Title", -2, HorizontalAlignment.Left);
            this.lvResult.Columns.Add("Alert Title", -2, HorizontalAlignment.Left);
            this.lvResult.Columns.Add("User Name", -2, HorizontalAlignment.Left);
            this.lvResult.Columns.Add("Status", -2, HorizontalAlignment.Left);
            this.lvResult.Columns.Add("List Name", -2, HorizontalAlignment.Left);
            this.lvResult.Columns.Add("URL", -2, HorizontalAlignment.Left);
            this.lvResult.Columns.Add("ID", -2, HorizontalAlignment.Left);
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            btnRemove.Enabled = false;
            txtemail.Visible = false;
            cbemail.Visible = false;
            btnSearch.Visible = false;
            btnRemove.Visible = false;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            lvResult.Items.Clear();
            //create a new thread to a method that shows form2, this is needed as the first(main thread) is busy
            //with the rest of the code, so this can be achived without hindering on the performance amd using 
            //ShowDialog();, without the thread the main form would be in a paused state and hangs up.
            System.Threading.Thread maint = new Thread(new ThreadStart(WorkThreadFunction));
            //whilst searching disable the parent form
            this.Enabled = false;
            //set this form to invisable
            this.Visible = false;
            //start the thread to show loading form
            maint.Start();

            try
            {
                using (SPSite site = new SPSite(txtUrl.Text))
                {
                    SPWebCollection collWebsites = site.AllWebs;
                    using (SPWeb web = site.OpenWeb())
                    {
                        listLists(web);
                    }
                }
            }
            catch (Exception a)
            {               
                maint.Interrupt();
                maint.Abort();
                this.Enabled = true;
                this.Show();
                this.Refresh();

                MessageBox.Show(a.Message);
            }

            //stop the other thread(loading) and show the partent form
            maint.Interrupt();
            maint.Abort();
            this.Enabled = true;
            this.Show();
            this.Refresh();

        }

        private static nfrom2 nfrom = new nfrom2();
        public static void WorkThreadFunction()
        {
            //show the loading form ShowDialog doesnt effect the main form as its running on another thread
            nfrom.ShowDialog();
        }

        private void listLists(SPWeb web)
        {
            
            SPAlertCollection collAlerts = web.Alerts;

            foreach (SPAlert oAlert in collAlerts)
            {
                //populate the list with the results

                if (cbemail.Checked == true)
                {
                    if (oAlert.User != null && oAlert.User.Email == txtemail.Text)
                    {
                        ListViewItem item = new ListViewItem(web.Title);
                        item.SubItems.Add(oAlert.Title);
                        item.SubItems.Add(oAlert.User.LoginName);
                        item.SubItems.Add(oAlert.Status.ToString());
                        item.SubItems.Add(oAlert.ListUrl);
                        item.SubItems.Add(web.Url);
                        item.SubItems.Add(oAlert.ID.ToString());
                        //add the items to the list
                        lvResult.Items.Add(item);
                        
                    }
                    else
                    {
                        if (oAlert.User == null)
                        {
                            ListViewItem item = new ListViewItem(web.Title);
                            item.SubItems.Add(oAlert.Title);
                            if (oAlert.User != null)
                            {
                                item.SubItems.Add(oAlert.User.LoginName);
                            }
                            else
                            {
                                item.SubItems.Add("System");
                            }
                            item.SubItems.Add(oAlert.Status.ToString());
                            item.SubItems.Add(oAlert.ListUrl);
                            item.SubItems.Add(web.Url);
                            item.SubItems.Add(oAlert.ID.ToString());
                            //add the items to the list
                            lvResult.Items.Add(item);
                            
                        }
                    }
                }
                else
                {
                    ListViewItem item = new ListViewItem(web.Title);
                    item.SubItems.Add(oAlert.Title);
                    if (oAlert.User != null)
                    {
                        item.SubItems.Add(oAlert.User.LoginName);
                    }
                    else
                    {
                        item.SubItems.Add("System");
                    }
                    item.SubItems.Add(oAlert.Status.ToString());
                    item.SubItems.Add(oAlert.ListUrl);
                    item.SubItems.Add(web.Url);
                    item.SubItems.Add(oAlert.ID.ToString());
                    //add the items to the list
                    lvResult.Items.Add(item);
                    
                }

            }
             
            //loop through each subweb of the web until there are no more subwebs
            foreach (SPWeb subWeb in web.Webs)
            {
                //call on itself for each subweb
                listLists(subWeb);
            }
        }

        private void cbemail_CheckedChanged(object sender, EventArgs e)
        {
            if (cbemail.Checked == true)
            {
                txtemail.Visible = true;
            }
            else
            {
                txtemail.Visible = false;
            }
        }

        private List<string> alertID = new List<string>();
        private void lvResult_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (this.lvResult.CheckedItems.Count != 0)
            {
                btnRemove.Enabled = true;
            }
            else
            {
                btnRemove.Enabled = false;
            }

            string ID = this.lvResult.Items[e.Item.Index].SubItems[6].Text;
            string webURL = this.lvResult.Items[e.Item.Index].SubItems[5].Text;
            if (e.Item.Checked == true)
            {

                if (!alertID.Exists(delegate(string p) { return p.Trim() == ID; }))
                {
                    alertID.Add(ID + ";" + webURL + ";" + e.Item.Index);
                }
            }
            else
            {
                if (alertID.Exists(delegate(string p) { return p.Trim() == ID; }))
                {
                    alertID.Remove(ID + ";" + webURL + ";" +e.Item.Index);
                }
            }
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            for (int i = alertID.Count -1; i > -1; i--)
            {
                string[] result = alertID[i].Split(';');
                System.Guid ID = new Guid (result[0].ToString());
                string webURL = result[1].ToString();
                int index = int.Parse(result[2]);

                using (SPSite mysite = new SPSite(webURL))
                {
                    using (SPWeb web = mysite.OpenWeb())
                    {
                        web.Alerts.Delete(ID);
                    }
                }
            }

            foreach (ListViewItem lvi in this.lvResult.CheckedItems)
            {
                this.lvResult.Items.Remove(lvi);
            }
        }

        private void txtUrl_TextChanged(object sender, EventArgs e)
        {
            if (txtUrl.TextLength != 0)
            {
                btnRemove.Visible = true;
                btnSearch.Visible = true;
                cbemail.Visible = true;
                if (cbemail.Checked == true)
                {
                    txtemail.Visible = true;
                }
            }
            else
            {
                btnRemove.Visible = false;
                btnSearch.Visible = false;
                cbemail.Visible = false;
                txtemail.Visible = false;
            }
        }
    }
}
